<script lang="ts" setup>
import { useRouteListener } from "@/hooks/useRouteListener"
import { compile } from "path-to-regexp"
import { ref } from "vue"
import { useRoute, useRouter, type RouteLocationMatched } from "vue-router"

const route = useRoute()
const router = useRouter()
const { listenerRouteChange } = useRouteListener()

/** 定义响应式数据 breadcrumbs，用于存储面包屑导航信息 */
const breadcrumbs = ref<RouteLocationMatched[]>([])
const mainBreadcrumbs = ref<string>() //主面包屑
const secondaryBreadcrumbs = ref<string>() //小面包屑

/** 获取面包屑导航信息 */
const getBreadcrumb = () => {
  breadcrumbs.value = route.matched.filter((item) => item.meta?.title && item.meta?.breadcrumb !== false)

  let pathName = breadcrumbs.value[0].name || ""
  // 知识库需要额外的设置小面包屑 这里需要加判断
  if (pathName === "KnowledgeDetails") {
    mainBreadcrumbs.value = (breadcrumbs.value[0].meta.title || "") as string
    secondaryBreadcrumbs.value = route.query.baseName as string
  } else {
    mainBreadcrumbs.value = ""
    secondaryBreadcrumbs.value = ""
  }
}

/** 编译路由路径 */
const pathCompile = (path: string) => {
  const toPath = compile(path)
  return toPath(route.params)
}

/** 处理面包屑导航点击事件 */
const handleLink = (item: RouteLocationMatched) => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect as string)
    return
  }
  router.push(pathCompile(path))
}

/** 监听路由变化，更新面包屑导航信息 */
listenerRouteChange((route) => {
  if (route.path.startsWith("/redirect/")) return
  getBreadcrumb()
}, true)
</script>

<template>
  <el-breadcrumb class="app-breadcrumb">
    <!-- <img :src="link" class="layout-logo" /> -->
    <el-breadcrumb-item class="breadcrumb-item" v-for="(item, index) in breadcrumbs" :key="item.path">
      <div class="dlink">
        <span v-if="item.redirect === 'noRedirect' || index === breadcrumbs.length - 1">
          {{ item.meta.title }}
        </span>
        <a v-else @click.prevent="handleLink(item)">
          {{ item.meta.title }}
        </a>
        <!-- <span class="f14999" v-if="!!mainBreadcrumbs">{{ mainBreadcrumbs }}3</span>
        <span class="f14333" v-if="!!secondaryBreadcrumbs"> / {{ secondaryBreadcrumbs }}4</span> -->
      </div>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<style lang="scss" scoped>
.app-breadcrumb {
  background-image: url("../../../assets/layouts/link.svg");
  background-repeat: no-repeat;
  background-position: 0 center;
  padding: 0 20px;

  span {
    color: var(--el-color-info);
    cursor: text;
    font-size: 18px;
    font-weight: 500;
  }
}

.dlink {
  display: flex;
}

.f14999 {
  margin-left: 30px;
}

.el-breadcrumb__inner,
.el-breadcrumb__inner a {
  font-weight: 400 !important;
}

.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: var(--v3-navigationbar-height);
  margin-left: 30px;
}
</style>
